package com.example.yichuangyun.mvvm.ui.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.recyclerview.widget.GridLayoutManager;

import com.example.yichuangyun.R;
import com.example.yichuangyun.config.Constant;
import com.example.yichuangyun.databinding.ActivityImproveCompanyInfoBinding;
import com.example.yichuangyun.dialog.SinglePickerView;
import com.example.yichuangyun.model.EventBusModel;
import com.example.yichuangyun.model.business.LabelModel;
import com.example.yichuangyun.mvvm.base.BaseActivity;
import com.example.yichuangyun.mvvm.ui.activity.view.ImproveCompanyInfoViewModel;
import com.example.yichuangyun.mvvm.ui.adapter.GridImageAdapter;
import com.example.yichuangyun.utils.CommonUtil;
import com.example.yichuangyun.utils.DensityUtil;
import com.example.yichuangyun.utils.FileUtil;
import com.example.yichuangyun.utils.ToastHelper;
import com.example.yichuangyun.utils.pictrue.GlideEngine;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.decoration.GridSpacingItemDecoration;
import com.luck.picture.lib.engine.CompressFileEngine;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnExternalPreviewEventListener;
import com.luck.picture.lib.style.PictureSelectorStyle;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import top.zibin.luban.Luban;
import top.zibin.luban.OnNewCompressListener;

/**
 * 完善企业信息
 */
@SuppressLint("NotifyDataSetChanged")
public class ImproveCompanyInfoActivity extends BaseActivity<ActivityImproveCompanyInfoBinding, ImproveCompanyInfoViewModel> {

    private final List<LabelModel> sourceData = new ArrayList<>();
    private final List<String> sourceStr = new ArrayList<>();
    private final List<LabelModel> typeData = new ArrayList<>();
    private final List<String> typeStr = new ArrayList<>();
    private int sourceId;
    private int improveType;
    private GridImageAdapter mAdapter;
    private ActivityResultLauncher<Intent> launcherResult;
    private String eid;
    private String creditNo;
    private MultipartBody.Part[] parts;

    @Override
    protected ImproveCompanyInfoViewModel bindModel() {
        return getViewModel(this, ImproveCompanyInfoViewModel.class);
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected void initData() {
        initTitleBar(getString(R.string.improve_company_info));
        sourceData.add(new LabelModel(context.getString(R.string.sao_lou), 1));
        sourceData.add(new LabelModel(context.getString(R.string.cold_call), 6));
        sourceData.add(new LabelModel(context.getString(R.string.mo_bai), 2));
        sourceData.add(new LabelModel(context.getString(R.string.xxhd), 3));
        sourceData.add(new LabelModel(context.getString(R.string.zjs), 4));
        sourceData.add(new LabelModel(context.getString(R.string.qi_ta), 5));
        for (LabelModel labelModel : sourceData) {
            sourceStr.add(labelModel.getRemark());
        }
        typeData.add(new LabelModel(context.getString(R.string.daily_visit), 5));
        typeData.add(new LabelModel(context.getString(R.string.realistic_photo), 1));
        typeData.add(new LabelModel(context.getString(R.string.physical_address), 2));
        typeData.add(new LabelModel(context.getString(R.string.member_info), 3));
        typeData.add(new LabelModel(context.getString(R.string.qi_ta), 4));
        for (LabelModel labelModel : typeData) {
            typeStr.add(labelModel.getRemark());
        }
        launcherResult = createActivityResultLauncher();
        binding.recyclerView.setLayoutManager(new GridLayoutManager(context, 4));
        binding.recyclerView.addItemDecoration(new GridSpacingItemDecoration(4,
                DensityUtil.dip2px(this, 8), false));
        mAdapter = new GridImageAdapter(context, onAddPicClickListener);
        binding.recyclerView.setAdapter(mAdapter);
        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            eid = bundle.getString(Constant.eidKey);
            creditNo = bundle.getString(Constant.creditNoKey);
        }
    }

    @Override
    protected void initClick() {
        viewModel.onDelayClick(binding.rlInfoSource, o -> {
            CommonUtil.closeKeyboard(this);
            initPickerView(0, sourceStr);
        });

        viewModel.onDelayClick(binding.rlType, o -> {
            CommonUtil.closeKeyboard(this);
            initPickerView(1, typeStr);
        });

        mAdapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                CommonUtil.closeKeyboard(ImproveCompanyInfoActivity.this);
                ArrayList<LocalMedia> selectList = (ArrayList<LocalMedia>) mAdapter.getData();
                if (selectList.size() > 0) {
                    PictureSelector.create(ImproveCompanyInfoActivity.this)
                            .openPreview()
                            .setImageEngine(GlideEngine.createGlideEngine())
                            .setExternalPreviewEventListener(new OnExternalPreviewEventListener() {
                                @Override
                                public void onPreviewDelete(int position) {
                                    mAdapter.remove(position);
                                    mAdapter.notifyItemRemoved(position);
                                }

                                @Override
                                public boolean onLongPressDownload(Context context, LocalMedia media) {  // 长按保存图片
                                    return true;
                                }
                            })
                            .startActivityPreview(position, true, selectList);
                }
            }

            @Override
            public void openPicture() {

            }
        });

        viewModel.onDelayClick(binding.btnConfirm, o -> {
            showLoadingDialog();
            if (null != parts && parts.length > 0) {
                viewModel.uploadImages(parts);
            } else {
                viewModel.saveCompanyInfo(eid, creditNo, improveType,
                        binding.etInfo.getText().toString().trim(), sourceId, viewModel.urls.getValue());
            }
        });

        viewModel.urls.observe(this, strings -> viewModel.saveCompanyInfo(eid, creditNo, improveType,
                binding.etInfo.getText().toString(), sourceId, viewModel.urls.getValue()));

        viewModel.uploadError.observe(this, s -> {
            ToastHelper.show(s);
            dismissLoadingDialog();
        });

        viewModel.infoError.observe(this, s -> {
            dismissLoadingDialog();
            ToastHelper.show(s);
        });
        viewModel.infoSuccess.observe(this, s -> {
            dismissLoadingDialog();
            ToastHelper.show(s);
            finish();
            EventBus.getDefault().post(new EventBusModel(Constant.refreshCustomList));
        });

        mAdapter.setOnDeleteClickListener((list, position) -> {
            parts = new MultipartBody.Part[list.size()];
            for (int i = 0; i < list.size(); i++) {
                LocalMedia media = list.get(i);
                File file = new File(media.getCompressPath() == null ? media.getRealPath() : media.getCompressPath());
                RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                MultipartBody.Part part = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
                parts[i] = part;
            }
        });

        binding.etInfo.setOnTextChangeListener(text -> {
            binding.tvTextCount.setText(getString(R.string.text_count_5, text.toString().trim().length()));
            changeBtnStatus();
        });
    }

    private void initPickerView(int flag, List<String> data) {
        SinglePickerView singlePickerView = new SinglePickerView(this, flag == 0 ? getString(R.string.info_source) : getString(R.string.improve_type), data) {
            @Override
            public void confirm(String label, int position) {
                if (flag == 0) {
                    binding.tvInfoSource.setText(label);
                    sourceId = sourceData.get(position).getNum();
                } else {
                    binding.tvType.setText(label);
                    improveType = typeData.get(position).getNum();
                }
                changeBtnStatus();
            }
        };
        singlePickerView.showSinglePickerView();
    }

    private final GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick() {
            PictureSelector.create(context).openGallery(SelectMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                    .setImageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                    .setSelectorUIStyle(new PictureSelectorStyle())
                    .setCameraImageFormat(PictureMimeType.PNG) // 拍照保存图片格式后缀,默认jpeg,Android Q使用PictureMimeType.PNG_Q
                    .isMaxSelectEnabledMask(true)
                    .setMaxSelectNum(9)
                    .setMinSelectNum(1)
                    .setSelectedData(mAdapter.getData())
                    .setCompressEngine((CompressFileEngine) (context, source, call) -> Luban.with(context).load(source).ignoreBy(100)
                            .setCompressListener(new OnNewCompressListener() {
                                @Override
                                public void onStart() {
                                }

                                @Override
                                public void onSuccess(String source, File compressFile) {
                                    if (call != null) {
                                        call.onCallback(source, compressFile.getAbsolutePath());
                                    }
                                }

                                @Override
                                public void onError(String source, Throwable e) {
                                    if (call != null) {
                                        call.onCallback(source, null);
                                    }
                                }
                            }).launch())
                    .forResult(launcherResult);
        }
    };

    private void changeBtnStatus() {
        if (!TextUtils.isEmpty(binding.etInfo.getText().toString().trim())
                && !TextUtils.isEmpty(binding.tvInfoSource.getText())
                && !TextUtils.isEmpty(binding.tvType.getText())) {
            binding.btnConfirm.setEnabled(true);
            binding.btnConfirm.setBackgroundResource(R.drawable.shape_button_sel);
        } else {
            binding.btnConfirm.setEnabled(false);
            binding.btnConfirm.setBackgroundResource(R.drawable.shape_button_def);
        }
    }

    /**
     * 创建一个ActivityResultLauncher
     */
    private ActivityResultLauncher<Intent> createActivityResultLauncher() {
        return registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    int resultCode = result.getResultCode();
                    if (resultCode == RESULT_OK) {
                        List<LocalMedia> selectList = PictureSelector.obtainSelectorList(result.getData());
                        parts = new MultipartBody.Part[selectList.size()];
                        for (int i = 0; i < selectList.size(); i++) {
                            LocalMedia media = selectList.get(i);
                            File file = new File(media.getCompressPath() == null ? media.getRealPath() : media.getCompressPath());
                            File file2 = new File(media.getRealPath());
                            try {
                                Log.e("@@@@@@@@@", "压缩前===" + FileUtil.getFileSize(file2) + "-----压缩后===" + FileUtil.getFileSize(file));
                                Log.e("@@@@@@@@@", "---------------------------");
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                            MultipartBody.Part part = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
                            parts[i] = part;
                        }

                        mAdapter.setList(selectList);
                        mAdapter.notifyDataSetChanged();
                    }
                });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (launcherResult != null) {
            launcherResult.unregister();
        }
    }
}